package com.xca.znb.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.entity.Collect;
import com.xca.znb.entity.Goods;
import com.xca.znb.entity.News;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.CollectImpl;
import com.xca.znb.presenter.CollectPresenter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class CollectionActivity extends AppCompatActivity {
    private ImageView backBtn ;
    private TextView managerBtn , goodsBtn , storeBtn , newsBtn ;
    private ListView listView ;
    private LinearLayout bottomView ;
    private Button delBtn ;
    private ArrayAdapter<Collect> adapter ;
    private List<Collect> goodsList ;
    private List<Collect> storeList ;
    private List<Collect> newsList ;
    private ArrayList<String> arrayId = new ArrayList<>();
    private CollectPresenter presenter ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.collection_activity);
        initView();

        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");

        goodsBtn.setSelected(true);

        CollectImpl collectImpl = new CollectImpl(this);
        presenter = new CollectPresenter(collectImpl);



        goodsList = presenter.getCollect(phone,"goods");
        storeList = presenter.getCollect(phone,"store");
        newsList = presenter.getCollect(phone,"news");

        goodsAdapter();

        goodsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodsBtn.setSelected(true);
                storeBtn.setSelected(false);
                newsBtn.setSelected(false);
                goodsAdapter();
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }
        });
        storeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodsBtn.setSelected(false);
                storeBtn.setSelected(true);
                newsBtn.setSelected(false);
                storeAdapter();
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }
        });
        newsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodsBtn.setSelected(false);
                storeBtn.setSelected(false);
                newsBtn.setSelected(true);
                newsAdapter();
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }
        });



            bottomView.setVisibility(View.GONE);
        managerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String managerBtnText = managerBtn.getText().toString();
                if (managerBtnText.equals("管理")){
                    managerBtn.setText("完成");
                    bottomView.setVisibility(View.VISIBLE);
                } else if (managerBtnText.equals("完成")) {
                    managerBtn.setText("管理");
                    bottomView.setVisibility(View.GONE);
                }
            }
        });


        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (arrayId != null){
                    new AlertDialog.Builder(CollectionActivity.this)
                            .setMessage("确定删除吗?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    for (String collectionId : arrayId){
                                        int cId = Integer.parseInt(collectionId);
                                        presenter.delCollect(cId);
                                    }
                                    arrayId.clear();
                                    refreshData();
                                    Toast.makeText(CollectionActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setNegativeButton("取消" , null).create().show();
                }
            }
        });


        listView.setAdapter(adapter);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (goodsBtn.isSelected()){
                    TextView gId = view.findViewById(R.id.collection_manager_goods_id);
                    String goodsId = gId.getText().toString();
                    Intent intent = new Intent(CollectionActivity.this,GoodsDetailActivity.class);
                    intent.putExtra("goodsId",goodsId);

                    int g_id = Integer.parseInt(goodsId);
                    SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                    String phone = sharedPreferences.getString("phone" , "");
                    LocalDateTime nowTime = LocalDateTime.now();
                    String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    presenter.addOrUpdateFoot(g_id,phone,secTime);

                    startActivity(intent);
                } else if (storeBtn.isSelected()) {
                    TextView gId = view.findViewById(R.id.collection_manager_store_id);
                    Intent intent = new Intent(CollectionActivity.this , EnterStoreActivity.class);
                  //  Toast.makeText(CollectionActivity.this, gId.getText().toString(), Toast.LENGTH_SHORT).show();
                    intent.putExtra("salesPhone" , gId.getText().toString());
                    startActivity(intent);
                } else if (newsBtn.isSelected()) {
                    TextView gId = view.findViewById(R.id.collection_manager_news_id);
                    Intent intent = new Intent(CollectionActivity.this , SchoolShowNews.class);
                    intent.putExtra("schoolFragment_showNews" , gId.getText().toString());
                    startActivity(intent);
                }

            }
        });

    }

    private void refreshData(){
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        goodsList = presenter.getCollect(phone,"goods");
        storeList = presenter.getCollect(phone,"store");
        newsList = presenter.getCollect(phone,"news");
        if (goodsBtn.isSelected()){
            goodsAdapter();
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else if (storeBtn.isSelected()) {
            storeAdapter();
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else if (newsBtn.isSelected()) {
            newsAdapter();
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
    }

    private void goodsAdapter(){
        adapter = new ArrayAdapter<Collect>(this , R.layout.collection_goods_item , R.id.collection_manager_goods_name , goodsList){
            public View getView(int position , View converView , ViewGroup parent){
                View view = super.getView(position, converView, parent);
                CheckBox goodsCheck = view.findViewById(R.id.collection_manager_goods_radio);
                ImageView goodsImg = view.findViewById(R.id.collection_manager_goods_img);
                TextView goodsName = view.findViewById(R.id.collection_manager_goods_name);
                TextView goodsId = view.findViewById(R.id.collection_manager_goods_id);
                TextView collectId = view.findViewById(R.id.collection_manager_goods_collectId);
                TextView goodsPrice = view.findViewById(R.id.collection_manager_goods_price);
                TextView goodsUnit = view.findViewById(R.id.collection_manager_goods_unit);
                TextView goodsType = view.findViewById(R.id.collection_manager_goods_type);
                Collect collect = getItem(position);
                assert collect != null;
                Goods goods = presenter.getGoodsById(Integer.parseInt(collect.getgID()));
                if (goods != null){
                    if (managerBtn.getText().toString().equals("管理")){
                        goodsCheck.setVisibility(View.GONE);
                    } else if (managerBtn.getText().toString().equals("完成")) {
                        goodsCheck.setVisibility(View.VISIBLE);
                        goodsCheck.setChecked(false);
                        goodsCheck.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (goodsCheck.isChecked()){
                                    arrayId.add(collectId.getText().toString());
                                } else {
                                    arrayId.remove(collectId.getText().toString());
                                }
                            }
                        });
                    }

                    Glide.with(CollectionActivity.this)
                                    .load(goods.getFirst_image())
                                            .into(goodsImg);
                  //  goodsImg.setImageResource(R.drawable.goods_managerment);//在这里放置图片
                    goodsName.setText(goods.getName());
                    goodsId.setText(String.valueOf(goods.getId()));
                    goodsPrice.setText(String.valueOf(goods.getPrice()));
                    goodsUnit.setText(goods.getUnit());
                    collectId.setText(String.valueOf(collect.getId()));
                    if (goods.getState().equals("已下架")){
                        goodsType.setText("已下架");
                    }else {
                        goodsType.setVisibility(View.GONE);
                    }
                }else {
                    presenter.delCollect(collect.getId());
                }
                return view ;
            }
        };
}
private void storeAdapter() {
    adapter = new ArrayAdapter<Collect>(this, R.layout.collection_store_item, R.id.collection_manager_store_name, storeList) {
        public View getView(int position, View converView, ViewGroup parent) {
            View view = super.getView(position, converView, parent);
            CheckBox storeCheck = view.findViewById(R.id.collection_manager_store_radio);
            ImageView storeImg = view.findViewById(R.id.collection_manager_store_img);
            TextView storeName = view.findViewById(R.id.collection_manager_store_name);
            TextView storeId = view.findViewById(R.id.collection_manager_store_id);
            TextView collectId = view.findViewById(R.id.collection_manager_store_collectId);
            Collect collect = getItem(position);
            assert collect != null;
            User user = presenter.getUserByPhone(collect.getgID());
            if (user != null){
                if (managerBtn.getText().toString().equals("管理")){
                    storeCheck.setVisibility(View.GONE);
                } else if (managerBtn.getText().toString().equals("完成")) {
                    storeCheck.setVisibility(View.VISIBLE);
                    storeCheck.setChecked(false);
                    storeCheck.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (storeCheck.isChecked()){
                                arrayId.add(collectId.getText().toString());
                            } else {
                                arrayId.remove(collectId.getText().toString());
                            }
                        }
                    });
                }

                Glide.with(CollectionActivity.this)
                                .load(user.getConcern())
                                        .into(storeImg);
               // storeImg.setImageResource(R.drawable.clearing_balance);
                if (user.getName() == null){
                    storeName.setText(collect.getgID());
                }else {
                    storeName.setText(user.getName());
                }
                storeId.setText(collect.getgID());
                collectId.setText(String.valueOf(collect.getId()));
            }

            return view ;
        }
    };
}



    private void newsAdapter() {
        adapter = new ArrayAdapter<Collect>(this, R.layout.collection_news_item, R.id.collection_manager_news_title, newsList) {
            public View getView(int position, View converView, ViewGroup parent) {
                View view = super.getView(position, converView, parent);
                CheckBox newsCheck = view.findViewById(R.id.collection_manager_news_radio);
                ImageView newsImg = view.findViewById(R.id.collection_manager_news_img);
                TextView newsTitle = view.findViewById(R.id.collection_manager_news_title);
                TextView newsId = view.findViewById(R.id.collection_manager_news_id);
                TextView collectId = view.findViewById(R.id.collection_manager_news_collectId);
                TextView newsTime = view.findViewById(R.id.collection_manager_news_time);
                Collect collect = getItem(position);
                assert collect != null;
                News news = presenter.getNewsById(Integer.parseInt(collect.getgID()));
                if (news != null){
                    if (managerBtn.getText().toString().equals("管理")){
                        newsCheck.setVisibility(View.GONE);
                    } else if (managerBtn.getText().toString().equals("完成")) {
                        newsCheck.setVisibility(View.VISIBLE);
                        newsCheck.setChecked(false);
                        newsCheck.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (newsCheck.isChecked()){
                                    arrayId.add(collectId.getText().toString());
                                } else {
                                    arrayId.remove(collectId.getText().toString());
                                }
                            }
                        });
                    }

                    Glide.with(CollectionActivity.this)
                                    .load(news.getImg())
                                            .into(newsImg);
                   // newsImg.setImageResource(R.drawable.add_image);//在这里设置图片
                    newsTitle.setText(news.getFirstTitle());
                    newsId.setText(String.valueOf(news.getId()));
                    collectId.setText(String.valueOf(collect.getId()));
                    newsTime.setText(news.getTime());
                }
                return view ;
            }
        };
    }



    private void initView(){
        backBtn = findViewById(R.id.collection_back) ;
        managerBtn = findViewById(R.id.collection_manager) ;
        goodsBtn = findViewById(R.id.collection_goods);
        storeBtn = findViewById(R.id.collection_store);
        newsBtn = findViewById(R.id.collection_news);
        listView = findViewById(R.id.collection_listView);
        bottomView = findViewById(R.id.collection_manager_bottom) ;
        delBtn = findViewById(R.id.collection_manager_del);
    }
}
